
import React, { PureComponent } from 'react'
import { Form, Input, Button, Radio, Row, Col } from 'antd';
import { connect } from 'react-redux'
const FormItem = Form.Item;
import dayjs from "dayjs";
import PageBackHeader from "@common/PageBackHeader";
import InputNumberWithSuffix from "@common/presentational/InputNumberWithSuffix";
import { withRouter } from 'react-router-dom'
import { getBilinInfo } from "@utils/localStorage";
import { COUPON_NAME_TYPE } from '@constants/ActivityListMap'
import DateRangePicker from "@common/presentational/DateRangePicker";
import { updateCoupons, createCoupons, publishCoupons } from "@sagas/marketing";
import { getHistoryMatchParams } from "@utils/setUrlQuery";
import { MultiSelectShelfProductModal } from "@common/presentational/MultiSelectModal";
import { priceFenToYuan, priceYuanToFen } from "@utils/priceConversion";
import notify from "@utils/tip";
import { CloseOutlined } from "@ant-design/icons";
const getReformedData = (data) => {
    const _data = {
        ...data,
        has_quota: data.quota ? true : false,
        price: data.offer_type === 'quota_cut' ? priceFenToYuan(data.price) : data.price / 10,
        use_period_type: data.use_period_type === "fixed_date" ? 'fixed_date' : (data.available_after_got_days === 1 ? 'since_got_1' : 'since_got_0'),
        maxium_got_frequency: data.maxium_got_frequency === 200 ? 200 : 'custom',
        off_maximum: data.off_maximum ? priceFenToYuan(data.off_maximum) : '',
        quota: data.quota ? priceFenToYuan(data.quota) : '',
        maxium_got_frequency_number: data.maxium_got_frequency,
        use_time: {
            startDate: dayjs(data.use_begined),
            endDate: dayjs(data.use_ended),
        }

    }
    return {
        ..._data
    }
}

const initialValue = {
    name: '',
    has_quota: false,
    scope: 'unlimited',
    use_period_type: 'fixed_date'
}
@connect(
    null
    , {
        updateCoupons,
        createCoupons,
        publishCoupons
    })
@withRouter
class MarketingCouponCreate extends PureComponent {

    constructor(props) {
        super(props);
        const { location } = props
        const { id, type } = getHistoryMatchParams(props)
        const { state } = location
        this.state = {
            id,
            type,
            formData: id ? {
                ...initialValue,
                ...getReformedData(state),
            } : {
                ...initialValue
            },
            productInfoList: id ? state.item_confs : []
        }

        this.formRef = React.createRef()
        this.multiSelectModalRef = React.createRef()

        this.handleSubmit = this.handleSubmit.bind(this)
        this.submitForm = this.submitForm.bind(this)
        this.cancelFunc = this.cancelFunc.bind(this)
    }

    showAddProductModal() {
        this.multiSelectModalRef.current?.show()
    }

    handleSubmit(values) {
        const { id, type, productInfoList } = this.state
        const { updateCoupons, createCoupons, publishCoupons } = this.props
        const pStoreId = getBilinInfo('storeId') || 0
        const owner_type = pStoreId ? 'store' : 'brand'
        const owner_id = pStoreId
        const params = {
            owner_type,
            owner_id,
            name: values.name,
            nature: 'voucher',
            offer_category: 'preferential',
            offer_type: type,
            need_verify_qualification: false,
            price: type === 'quota_cut' ? priceYuanToFen(values.price) : values.price * 10,
            use_period_type: values.use_period_type === 'fixed_date' ? 'fixed_date' : 'since_got',
            use_scenes: ['ordering'],
            scope: values.scope,
            maxium_got_frequency: values.maxium_got_frequency === 'custom' ? parseInt(values.maxium_got_frequency_number) : 200
        }
        if (values.has_quota) {
            params.quota = priceYuanToFen(parseInt(values.quota))
        }
        if (type === 'discount' && values.off_maximum) {
            params.off_maximum = priceYuanToFen(parseInt(values.off_maximum))
        }
        if (values.use_period_type === 'fixed_date') {
            params.use_begined = new Date(values.use_time.startDate).toISOString()
            params.use_ended = new Date(values.use_time.endDate).toISOString()
        } else {
            params.available_after_got_days = values.use_period_type === 'since_got_0' ? 0 : 1,
                params.days = values.days
        }
        if (values.scope === 'include_items') {
            if (!productInfoList.length) {
                notify('请选择商品', 'error')
                return false
            }
            params.item_confs = productInfoList
        }
        if (values.scope === 'exclude_items') {
            if (!productInfoList.length) {
                notify('请选择商品', 'error')
                return false
            }
            params.item_confs = productInfoList
        }
        if (id) {
            params.id = id
            updateCoupons(params, () => {
                this.cancelFunc()
            })
        } else {
            const that = this
            createCoupons(params, (res) => {
                publishCoupons({
                    id: res.coupon?.id
                }, () => {
                    that.cancelFunc()
                })
            })
        }
    }

    deleteItems(index) {
        this.setState({
            productInfoList: [
                ...this.state.productInfoList.slice(0, index),
                ...this.state.productInfoList.slice(index + 1)
            ]
        })
    }

    submitForm() {
        this.formRef.current?.submit()
    }

    cancelFunc() {
        this.props.goBack ? this.props.goBack() : this.props.history.goBack()
    }

    handleProductChange(value) {
        this.setState({
            productInfoList: value
        })
    }
    render() {
        const { formData, id, type, productInfoList } = this.state
        const isEdit = !!id
        return (
            <div className="bilin-web">
                <PageBackHeader title={isEdit ? `编辑${COUPON_NAME_TYPE[type]}` : `新建${COUPON_NAME_TYPE[type]}`} />
                <div className="bilin-web-body form-page with-footer">
                    <Form
                        ref={this.formRef}
                        name="coupon-form"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        initialValues={formData}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                        onFinish={this.handleSubmit}
                    >
                        <div className="ft-16 pdb-36">基本信息</div>
                        <FormItem
                            label="优惠券名称: "
                            name='name'
                            rules={[
                                { required: true, message: '请输入名称', },
                            ]}
                        >
                            <Input placeholder="如：三周年全场满减券，最多24个字" maxLength={24} />
                        </FormItem>
                        <FormItem
                            label="使用时间: "
                            name='use_period_type'
                            rules={[
                                { required: true, message: '请选择使用时间类型', },
                            ]}
                        >
                            <Radio.Group >
                                <Radio value='fixed_date'>指定日期</Radio>
                                <Radio value='since_got_0'>领取后当日</Radio>
                                <Radio value='since_got_1'>领取后次日</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.use_period_type !== currentValues.use_period_type}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('use_period_type') === 'fixed_date' ? (<>
                                    <Row>
                                        <Col span={4} />
                                        <Col span={20}>
                                            <FormItem
                                                name='use_time'
                                                rules={[
                                                    { required: true, message: '请选择有效期', },
                                                ]}
                                            >
                                                <DateRangePicker />
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.use_period_type !== currentValues.use_period_type}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('use_period_type') === 'since_got_0' || getFieldValue('use_period_type') === 'since_got_1' ? (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        <Col span={2}>
                                            <span>有效天数</span>
                                        </Col>
                                        <Col span={18}>
                                            <FormItem
                                                name='days'
                                                noStyle
                                                rules={[
                                                    { required: true, message: '请输入天数', },
                                                ]}
                                            >
                                                <InputNumberWithSuffix
                                                    min={1}
                                                    max={100000}
                                                    step={1}
                                                    precision={0}
                                                    placeholder="请输入"
                                                    style={{ width: '280px' }}
                                                    suffix={(
                                                        <span>天</span>
                                                    )}
                                                />
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <div className="ft-16 pdb-36">使用规则</div>
                        <FormItem
                            label="优惠内容: "
                            name='has_quota'
                            rules={[
                                { required: true, message: '请选择优惠内容类型', },
                            ]}
                        >
                            <Radio.Group>
                                <Radio value={false}>无使用门槛</Radio>
                                <Radio value={true}>有使用门槛</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.has_quota !== currentValues.has_quota}
                        >
                            {({ getFieldValue }) => {
                                return (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        {getFieldValue('has_quota') && <>
                                            <Col span={10}>
                                                <FormItem
                                                    label='金额满'
                                                    name='quota'
                                                    labelCol={{ span: 6 }}
                                                    wrapperCol={{ span: 18 }}
                                                    rules={[
                                                        { required: true, message: '请输入金额', },
                                                    ]}
                                                >
                                                    <InputNumberWithSuffix
                                                        min={0.01}
                                                        max={100000}
                                                        step={1}
                                                        precision={2}
                                                        placeholder="请输入金额"
                                                        style={{ width: '230px' }}
                                                        suffix={(
                                                            <span>元</span>
                                                        )}
                                                    />
                                                </FormItem>
                                            </Col>
                                        </>}
                                        {type === 'quota_cut' && <>
                                            <Col span={9}>
                                                <FormItem
                                                    label='减免金额'
                                                    name='price'
                                                    labelCol={{ span: 6 }}
                                                    wrapperCol={{ span: 18 }}
                                                    rules={[
                                                        { required: true, message: '请输入金额', },
                                                    ]}
                                                >
                                                    <InputNumberWithSuffix
                                                        min={0.01}
                                                        max={100000}
                                                        step={1}
                                                        precision={2}
                                                        placeholder="请输入金额"
                                                        style={{ width: '280px' }}
                                                        suffix={(
                                                            <span>元</span>
                                                        )}
                                                    />
                                                </FormItem>
                                            </Col>
                                        </>}
                                        {type === 'discount' && <>
                                            <Col span={9}>
                                                <FormItem
                                                    label='折扣优惠'
                                                    name='price'
                                                    labelCol={{ span: 6 }}
                                                    wrapperCol={{ span: 18 }}
                                                    rules={[
                                                        { required: true, message: '请输入折扣', },
                                                    ]}
                                                >
                                                    <InputNumberWithSuffix
                                                        min={0.1}
                                                        max={9.9}
                                                        step={1}
                                                        precision={1}
                                                        placeholder="请输入折扣"
                                                        style={{ width: '280px' }}
                                                        suffix={(
                                                            <span>折</span>
                                                        )}
                                                    />
                                                </FormItem>
                                            </Col>
                                        </>}
                                    </Row>
                                </>
                                )
                            }}
                        </Form.Item>
                        {type === 'discount' && <>
                            <FormItem
                                label='折扣优惠上限'
                                name='off_maximum'
                                rules={[
                                    { required: true, message: '请输入折扣上限' },
                                ]}
                            >
                                <InputNumberWithSuffix
                                    min={0.01}
                                    max={100000}
                                    step={1}
                                    precision={2}
                                    placeholder="请输入金额"
                                    style={{ width: '280px' }}
                                    suffix={(
                                        <span>元</span>
                                    )}
                                />
                            </FormItem>
                        </>}
                        <FormItem
                            label="适用商品: "
                            name='scope'
                            rules={[
                                { required: true, message: '请选择类型', },
                            ]}
                        >
                            <Radio.Group>
                                <Radio value='unlimited'>全部商品</Radio>
                                <Radio value='include_items'>指定商品可用</Radio>
                                <Radio value='exclude_items'>指定商品不可用</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.scope !== currentValues.scope}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('scope') !== 'unlimited' ? (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        <Col span={20}>
                                            <Button type="primary" ghost onClick={this.showAddProductModal.bind(this)}>+ 添加商品</Button>
                                            {productInfoList.length ? <div className='mgt-16 market-product-list'>
                                                {productInfoList.map((item, index) => (<div key={index} className='market-product-item'>
                                                    <div>{item.name}</div>
                                                    <div>
                                                        <CloseOutlined className="cur-poi ft-12 ft-clr-ml" onClick={this.deleteItems.bind(this, index)} />
                                                    </div>
                                                </div>))}
                                            </div> : null}
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                        <FormItem
                            label="领取限制: "
                            name='maxium_got_frequency'
                            rules={[
                                { required: true, message: '请选择类型', },
                            ]}
                        >
                            <Radio.Group>
                                <Radio value={200}>不限次数（最多200张）</Radio>
                                <Radio value='custom'>每人限领</Radio>
                            </Radio.Group>
                        </FormItem>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.maxium_got_frequency !== currentValues.maxium_got_frequency}
                        >
                            {({ getFieldValue }) => {
                                return getFieldValue('maxium_got_frequency') === 'custom' ? (<>
                                    <Row className='flex-vertical-center'>
                                        <Col span={4} />
                                        <Col span={20}>
                                            <FormItem
                                                name='maxium_got_frequency_number'
                                                extra='每人限领次数对用户主动领取时生效，活动发放时不生效。'
                                                rules={[
                                                    { required: true, message: '请输入张数', },
                                                ]}
                                            >
                                                <Input placeholder="请输入" maxLength={5} suffix={<span>张</span>} />
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </>
                                ) : null
                            }}
                        </Form.Item>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button type="primary" ghost onClick={this.cancelFunc}>取消</Button>
                    <Button type="primary" onClick={this.submitForm}>保存</Button>
                </div>
                <MultiSelectShelfProductModal
                    ref={this.multiSelectModalRef}
                    title="添加商品"
                    onChange={this.handleProductChange.bind(this)}
                    initSelectedInfo={productInfoList}
                />
            </div>
        )
    }
}

export default MarketingCouponCreate